package com.wolfalpha.utron.activity;

import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.base.BaseNormalActivity;
import com.wolfalpha.utron.adapter.ItemProjectCommentBaseAdapter;
import com.wolfalpha.utron.app.AppConfig;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.bean.ItemProjectComment;
import com.wolfalpha.utron.service.ProjectService;
import com.wolfalpha.utron.service.impl.ProjectServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.InputTools;
import com.wolfalpha.utron.utils.StringUtils;
import com.wolfalpha.utron.utils.ThreadPoolUtils;
import com.wolfalpha.utron.view.CircleImageView;
import com.wolfalpha.utron.view.ScrollXListView;
import com.wolfalpha.utron.view.XListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目评论详情界面
 * <p/>
 * Created by luodon on 15/9/12.
 */

public class ProjectReplyDetailActivity extends BaseNormalActivity implements OnClickListener, XListView.IXListViewListener {

    private EditText etCConetent;       //回复内容
    private Button btnSend;             //标题
    private LinearLayout llInfo;          //内容布局

    private ScrollView scrollView;
    private LinearLayout root;
    private ScrollXListView lvComments;        //评论列表控件

    private ItemProjectComment firstComment = null;
    private int pId = 0;

    private ProjectService projectService;

    private List<ItemProjectComment> comments = new ArrayList<ItemProjectComment>();

    private ItemProjectCommentBaseAdapter commentAdapter;

    private CircleImageView cvHead;     //头像
    private TextView tvName;            //姓名
    private TextView tvContent;         //内容
    private TextView tvTime;            //时间
    private TextView tvRcount;          //回复数量


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        if (bundle == null || !bundle.containsKey("reply")) {
            finish();
            return;
        }
        firstComment = (ItemProjectComment) bundle.getSerializable("reply");
        pId = bundle.getInt("pId");

        setContentView(R.layout.activity_idea_reply_personal);
        projectService = new ProjectServiceImpl();

        intiView();
        initListeners();

    }


    private final static int IPUT_SHOW = 1;     //输入法打开
    private final static int IPUT_DISMISS = 2; //输入法隐藏
    private final int LOAD_MORE = 3;    //加载更多
    private final int LOAD_REFRESH = 4; //刷新

    private boolean ipuitShowing = false;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case IPUT_SHOW:
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    layoutParams.setMargins(0, 0, 0, msg.arg1);
                    llInfo.setLayoutParams(layoutParams);
                    llInfo.invalidate();
                    break;
                case IPUT_DISMISS:
                    LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    layoutParams1.setMargins(0, 0, 0, 0);
                    llInfo.setLayoutParams(layoutParams1);
                    llInfo.invalidate();
                    etCConetent.setText("");
                    InputTools.HideKeyboard(etCConetent);
                    onRefresh();
                    break;
                case LOAD_REFRESH:
                    commentAdapter.setData(comments);
                    lvComments.stopRefresh();
                    break;
                case LOAD_MORE:
                    commentAdapter.setData(comments);
                    lvComments.stopLoadMore();
                    break;
            }

        }
    };

    private boolean inputIsShowing = false;

    private int page = 1;

    /**
     * 初始化界面
     */
    private void intiView() {
        setTvTitle("评论详情");
        root = (LinearLayout) findViewById(R.id.ll_idea_reply_personal_root);
        scrollView = (ScrollView) findViewById(R.id.sc_idea_reply_detail_content);
        llInfo = (LinearLayout) findViewById(R.id.ll_edit_idea_reply_personal);
        etCConetent = (EditText) findViewById(R.id.et_idea_reply_detail_comment_content);
        btnSend = (Button) findViewById(R.id.btn_idea_reply_detail_comment_send);
        lvComments = (ScrollXListView) findViewById(R.id.slv_idea_personal_reply_detail);
        commentAdapter = new ItemProjectCommentBaseAdapter(ProjectReplyDetailActivity.this, comments);
        commentAdapter.setShowReplyed(false);
        lvComments.setAdapter(commentAdapter);
        lvComments.setPullLoadEnable(true);
        lvComments.setXListViewListener(this);

        cvHead = (CircleImageView) findViewById(R.id.item_iv_idea_comment_user_head);
        tvName = (TextView) findViewById(R.id.item_tv_idea_comment_user_name);
        tvContent = (TextView) findViewById(R.id.item_tv_idea_comment_content);
        tvTime = (TextView) findViewById(R.id.item_tv_idea_comment_time);
        tvRcount = (TextView) findViewById(R.id.item_tv_idea_comment_num);

        Picasso.with(this)
                .load(firstComment.getUser_head())
                .placeholder(R.mipmap.head_default)
                .into(cvHead);
        tvName.setText(firstComment.getUser_name());
        tvContent.setText(firstComment.getContent());
        tvTime.setText(StringUtils.friendly_time(StringUtils.TimeStamp2Date(firstComment.getTime() * 1000)));
        tvRcount.setText(firstComment.getReplys() + "");

        /**
         * 监听键盘状态，改变输入框的位置
         */
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                root.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom;
                //若不可视区域高度大于100，则键盘显示
                if (rootInvisibleHeight > 200) {
                    if (!inputIsShowing) {
                        Message message = new Message();
                        message.what = IPUT_SHOW;
                        message.arg1 = rootInvisibleHeight;
                        handler.sendMessage(message);
                        inputIsShowing = true;
                    }
                } else {
                    //键盘隐藏
                    if (inputIsShowing) {
                        handler.sendEmptyMessage(IPUT_DISMISS);
                        inputIsShowing = false;
                    }

                }
            }
        });
        onRefresh();
    }

    /**
     * 初始化监听
     */

    private void initListeners() {
        btnSend.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_idea_reply_detail_comment_send:
                //发布回复

                //该功能必须登录
                if (!AppContext.getInstance().getIsLogined()) {
                    UIHelper.showNotLogined(ProjectReplyDetailActivity.this);
                    return;
                }

                sendReply();
                break;
        }
    }

    /**
     * 发送
     */
    private void sendReply() {
        if (TextUtils.isEmpty(etCConetent.getText().toString().trim())) {
            return;
        } else {
            ThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    boolean b = projectService.doComment(pId, etCConetent.getText().toString().trim(), firstComment.getId());
                    if (!b) {
                        //回复失败
                        UIHelper.ToastMessage(ProjectReplyDetailActivity.this, "回复失败，请重试");
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvRcount.setText(firstComment.getReplys().size() + 1 + "");
                            }
                        });
                        handler.sendEmptyMessage(IPUT_DISMISS);
                    }
                }
            });
        }
    }

    @Override
    public void onRefresh() {
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                comments = projectService.getComments(pId, page, firstComment.getId());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (comments != null) {
                            commentAdapter.setData(comments);
                            if (comments.size() < AppConfig.COMMENT_PAGE_SIZE) {
                                lvComments.setPullLoadEnable(false);
                            } else {
                                lvComments.setPullLoadEnable(true);
                            }
                        } else {
                            lvComments.setPullLoadEnable(false);
                        }
                        lvComments.stopRefresh();
                    }
                });

            }
        });
    }

    @Override
    public void onLoadMore() {
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                final List<ItemProjectComment> comments1 = projectService.getComments(pId, ++page, firstComment.getId());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (comments1 != null) {
                            comments.addAll(comments1);
                            commentAdapter.setData(comments);
                            if (comments1.size() < AppConfig.COMMENT_PAGE_SIZE) {
                                lvComments.setPullLoadEnable(false);
                            } else {
                                lvComments.setPullLoadEnable(true);
                            }
                        } else {
                            page--;
                            lvComments.setPullLoadEnable(false);
                        }
                        lvComments.stopLoadMore();
                    }
                });
            }
        });
    }
}
